package com.cheng.im.gateway.handler;

import com.cheng.im.common.bean.msg.ProtoMsg;
import com.cheng.im.common.bean.msg.ProtoMsgV1;
import com.cheng.im.common.cocurrent.FutureTaskScheduler;
import com.cheng.im.gateway.processer.ChatRedirectProcessor;
import com.cheng.im.gateway.session.LocalSession;
import com.cheng.im.gateway.session.ServerSession;
import com.cheng.im.gateway.session.manager.SessionManger;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Slf4j
@Service("ChatRedirectHandler")
@ChannelHandler.Sharable
public class ChatRedirectHandler extends ChannelInboundHandlerAdapter
{

    @Autowired
    ChatRedirectProcessor redirectProcessor;

    @Autowired
    SessionManger sessionManger;

    /**
     * 收到消息
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception
    {
        //判断消息实例
        if (null == msg || !(msg instanceof ProtoMsgV1.Message))
        {
            super.channelRead(ctx, msg);
            return;
        }

        // todo:消息类型改造，先处理单聊和群聊
        // 判断消息类型
        ProtoMsgV1.Message pkg = (ProtoMsgV1.Message) msg;
        ProtoMsgV1.HeadType headType = ((ProtoMsgV1.Message) msg).getType();

        if (headType.equals((ProtoMsgV1.HeadType.MESSAGE_REQUEST))) {
            // 异步处理转发的逻辑
            FutureTaskScheduler.add(() ->
            {
                // 判断是否登录,如果登录了，则为用户消息
                LocalSession session = LocalSession.getSession(ctx);
                if (null != session && session.isLogin())
                {
                    redirectProcessor.action(session, pkg);
                    return;
                }

                String sessionId = pkg.getSessionId();
                ServerSession sessionBySession = SessionManger.inst().getSessionBySession(sessionId);
                if (sessionBySession instanceof LocalSession)
                // 将IM消息发送到接收方
                {
                    sessionBySession.writeAndFlush(pkg);
                }
            });
        } else if (headType.equals((ProtoMsgV1.HeadType.MESSAGE_NOTIFICATION))) {
            // 通知消息
        }

        super.channelRead(ctx, msg);
    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx)
            throws Exception
    {
        LocalSession session = ctx.channel().attr(LocalSession.SESSION_KEY).get();

        if (null != session && session.isValid())
        {
            session.close();
            sessionManger.removeSession(session.getSessionId(), session.getUser().getAppId());
        }
    }
}
